import { useState, useEffect, useCallback } from 'react';
import { View, Text, Button } from '@tarojs/components';
import { Tabs, Swiper } from '@nutui/nutui-react-taro';
import Taro, { useShareAppMessage, useDidShow } from '@tarojs/taro';
import { BasicLayout } from '@/layouts';
import { Media, Icon, Empty } from '@/components';
import { useRequest } from '@/hooks';
import { getApiChoiceOutCompanyInfoCompanyId, getApiChoiceOutDressListCompanyId, getApiChoiceOutPersonListCompanyId } from '@/api'
import { DressType, dressTypeList } from '@/interfaces/dress';
import { FourGreatEnum } from '@/interfaces/fourGreat';
import { RouterUtil, formatAppLoadParams, TabbarUtil } from '@/utils';
import styles from './index.module.scss';
import { StorageKey } from '@/constants/storage';
import { isEmpty } from 'lodash-es';
import type { AppLoadParamsProps } from '@/interfaces/base';
import { DEFAULT_SHOP_ID } from '@/constants';
import { usePreselectStore } from '@/models';

const windowWidth = Taro.getSystemInfoSync().windowWidth;

// 四大金刚类型列表
const fourGreatTypeList = Object.entries(FourGreatEnum)
  .filter(([key]) => isNaN(Number(key)))
  .map(([key, value]) => ({
    text: key,
    value: value,
  }));

function Home() {

  const [activeTab, setActiveTab] = useState<number>(DressType.婚纱);
  const [activeMakeupTab, setActiveMakeupTab] = useState<number>(
    FourGreatEnum.化妆师,
  );

  const [shopId, setShopId] = useState<number>(Number(Taro.getStorageSync(StorageKey.SHOP_ID)) || Number(DEFAULT_SHOP_ID));
  const { dresses, persons } = usePreselectStore();

  useDidShow(() => {
    handleStartParams();
    // 更新 tabbar badge
    const totalCount = dresses.length + persons.length;
    TabbarUtil.setPreselectBadge(totalCount);
  })

  // 处理启动参数
  const handleStartParams = useCallback(() => {
    const options = Taro.getLaunchOptionsSync();
    let optionsQuery = options?.query;
    // 二次扫码参数
    const enterOptionsQuery = Taro.getEnterOptionsSync()?.query ?? {};
    if (!isEmpty(enterOptionsQuery)) {
      optionsQuery = enterOptionsQuery;
    }
    const params: AppLoadParamsProps = formatAppLoadParams(optionsQuery);
    const _shopId = Taro.getStorageSync(StorageKey.SHOP_ID) || DEFAULT_SHOP_ID;
    
    // 检查是否存在 shopId 参数
    const hasShopId = !!(params.shopId || optionsQuery?.shopId || _shopId);
    console.log('检测到 shopId:', hasShopId, params.shopId || optionsQuery?.shopId, _shopId);
    
    // 存储 shopId 状态，用于控制 tabbar 显示
    Taro.setStorageSync(StorageKey.HAS_SHOP_ID, hasShopId);
    
    if (hasShopId) {
      // 存储 shopId
      Taro.setStorageSync(StorageKey.SHOP_ID, params.shopId || optionsQuery?.shopId || _shopId);
      setShopId(params.shopId || optionsQuery?.shopId || _shopId);
    }
  }, []);

  // 分享功能
  useShareAppMessage(() => {
    return {
      title: `${companyInfo?.name || '店铺'} - 欢迎光临`,
      path: `/pages/home/index/index?shopId=${shopId}`,
      imageUrl: '',
    };
  });

  // 获取公司信息
  const { data: companyInfo, run: fetchCompanyInfo } = useRequest(getApiChoiceOutCompanyInfoCompanyId, {
    formatResult: (res) => res.data,
    manual: true,
  });

  // 获取婚纱列表
  const { data: dressList = [], run: fetchDressList } = useRequest(
    getApiChoiceOutDressListCompanyId,
    {
      manual: true,
      formatResult: (res) => {
        // 只取前4条
        return (res?.data?.data || []).slice(0, 4);
      },
    },
  );

  // 获取四大金刚数据
  const { data: makeupList = [], run: fetchMakeupList } = useRequest(
    getApiChoiceOutPersonListCompanyId,
    {
      manual: true,
      formatResult: (res) => {
        // 只取前4条
        return (res?.data || []).slice(0, 4);
      },
    },
  );

  useEffect(() => {
    fetchCompanyInfo({ companyId: shopId });
  }, [shopId])


  // 当婚纱tab切换时，重新获取对应类型的婚纱列表
  useEffect(() => {
    fetchDressList({ dressType: activeTab, companyId: shopId });
  }, [activeTab, shopId]);

  // 当化妆摄影tab切换时，重新获取对应类型的数据
  useEffect(() => {
    fetchMakeupList({ type: activeMakeupTab, companyId: shopId });
  }, [activeMakeupTab, shopId]);

  // 解析bannerList
  const getBannerList = () => {
    const info = companyInfo as any;
    if (!info?.bannerList) return [];
    try {
      const parsed = JSON.parse(info.bannerList);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  };

  const bannerList = getBannerList();

  // 解析四大金刚的图片
  const getMakeupPictureUrl = (item: any) => {
    if (!item?.bizData) return '';
    try {
      const bizData = JSON.parse(item.bizData);
      if (bizData?.pictureUrl && Array.isArray(bizData.pictureUrl)) {
        return bizData.pictureUrl[0] || '';
      }
    } catch {
      return '';
    }
    return '';
  };

  return (
    <BasicLayout title="" className={styles.container} safeArea={false} hasTabbar>
      {/* 店铺信息模块 */}
      <View className={styles.shopSection}>
        {/* Banner轮播 */}
        {bannerList.length > 0 ? (
          <Swiper
            className={styles.bannerWrapper}
            height={windowWidth}
            indicator
            loop
            autoPlay
            duration={3000}
          >
            {bannerList.map((banner, index) => (
              <Swiper.Item key={index}>
                <Media
                  className={styles.bannerImage}
                  src={banner}
                  width="100vw"
                  height={`${windowWidth}px`}
                  mode="aspectFill"
                  controls={false}
                  style={{
                    borderRadius: 0,
                  }}
                />
              </Swiper.Item>
            ))}
          </Swiper>
        ) : (
          <View className={styles.bannerPlaceholder}>
            <Text className={styles.placeholderText}>暂无Banner图片</Text>
          </View>
        )}

        {/* 店铺基本信息 */}
        <View className={styles.shopInfo}>
          <Text className={styles.shopName}>{companyInfo?.name}</Text>
          {companyInfo?.intro && (
            <Text className={styles.shopIntro}>{companyInfo.intro}</Text>
          )}
        </View>

        {/* 店铺联系方式 */}
        <View className={styles.contactSection}>
          <View className={styles.contactGrid}>
            {/* 电话 */}
            <View
              className={styles.contactButton}
              onClick={() => {
                if (companyInfo?.contactPhone) {
                  Taro.showModal({
                    title: '电话',
                    content: companyInfo.contactPhone,
                    showCancel: true,
                    cancelText: '关闭',
                    confirmText: '拨打',
                    success: (res) => {
                      if (res.confirm) {
                        // 拨打
                        Taro.makePhoneCall({
                          phoneNumber: companyInfo.contactPhone,
                        });
                      }
                    },
                  });
                }
              }}
            >
              <View className={styles.contactIconWrapper}>
                <Icon name="PhoneOutlined" size={16} />
              </View>
              <Text className={styles.contactButtonText}>电话</Text>
            </View>

            {/* 微信 */}
            <View
              className={styles.contactButton}
              onClick={() => {
                const info = companyInfo as any;
                if (info?.weiAccount) {
                  Taro.showModal({
                    title: '微信',
                    content: info.weiAccount,
                    showCancel: true,
                    cancelText: '关闭',
                    confirmText: '复制',
                    success: async (res) => {
                      if (res.confirm) {
                        // 复制
                        await Taro.setClipboardData({
                          data: info.weiAccount,
                        });
                        Taro.showToast({
                          title: '已复制',
                          icon: 'success',
                          duration: 2000,
                        });
                      }
                    },
                  });
                }
              }}
            >
              <View className={styles.contactIconWrapper}>
                <Icon name="WeChatOutlined" size={16} />
              </View>
              <Text className={styles.contactButtonText}>微信</Text>
            </View>

            {/* 营业时间 */}
            <View
              className={styles.contactButton}
              onClick={() => {
                if (companyInfo?.invitationCode) {
                  Taro.showModal({
                    title: '营业时间',
                    content: companyInfo.invitationCode,
                    showCancel: false,
                    confirmText: '确定',
                  });
                }
              }}
            >
              <View className={styles.contactIconWrapper}>
                <Icon name="TimeOutlined" size={16} />
              </View>
              <Text className={styles.contactButtonText}>营业时间</Text>
            </View>

            {/* 地址 */}
            <View
              className={styles.contactButton}
              onClick={() => {
                const info = companyInfo as any;
                if (info?.address) {
                  // 构建完整地址显示（组合省市区和详细地址）
                  const fullAddress = info.address;
                  
                  Taro.showModal({
                    title: '地址',
                    content: fullAddress,
                    showCancel: true,
                    cancelText: '关闭',
                    confirmText: '复制',
                    success: async (res) => {
                      if (res.confirm) {
                        // 尝试打开地图导航
                        // 检查是否有经纬度信息
                        const latitude = info.latitude || info.lat;
                        const longitude = info.longitude || info.lng || info.lon;
                        
                        if (latitude && longitude) {
                          // 有经纬度，打开地图导航
                          try {
                            await Taro.openLocation({
                              latitude: Number(latitude),
                              longitude: Number(longitude),
                              name: info.name || companyInfo?.name || '店铺地址',
                              address: fullAddress,
                              scale: 18,
                            });
                          } catch (error) {
                            console.error('打开地图失败:', error);
                            // 如果打开地图失败，改为复制
                            await Taro.setClipboardData({
                              data: fullAddress,
                            });
                            Taro.showToast({
                              title: '已复制',
                              icon: 'success',
                              duration: 2000,
                            });
                          }
                        } else {
                          // 没有经纬度，使用复制功能
                          await Taro.setClipboardData({
                            data: fullAddress,
                          });
                          Taro.showToast({
                            title: '已复制',
                            icon: 'success',
                            duration: 2000,
                          });
                        }
                      }
                    },
                  });
                }
              }}
            >
              <View className={styles.contactIconWrapper}>
                <Icon name="PlaceOutlined" size={16} />
              </View>
              <Text className={styles.contactButtonText}>地址</Text>
            </View>

            {/* 分享 */}
            <Button
              className={styles.contactButton}
              // fill="none"
              openType="share"
            >
              <View className={styles.contactIconWrapper}>
                <Icon name="ShareOutlined2" size={16} />
              </View>
              <Text className={styles.contactButtonText}>分享</Text>
            </Button>
          </View>
        </View>
      </View>

      {/* 婚纱礼服模块 */}
      <View className={styles.dressSection}>
        <View className={styles.sectionHeader}>
          <Text className={styles.sectionTitle}>婚纱礼服</Text>
          {dressList.length > 0 && (
            <View
              className={styles.moreIcon}
              onClick={() => {
                RouterUtil.switchTab('/pages/dress/index/index', {
                  pageType: 0,
                });
              }}
            >
              <Icon name="RightOutlined" size={16} />
            </View>
          )}
        </View>

        <Tabs
          value={activeTab}
          onChange={(v: number) => setActiveTab(v)}
          className={styles.dressTabs}
        >
          {dressTypeList.map((item, index) => (
            <Tabs.TabPane title={item.text} value={item.value} key={index}>
              <View className={styles.dressGrid}>
                {dressList.length > 0 ? (
                  dressList.map((dress) => (
                    <View
                      key={dress.id}
                      className={styles.dressCard}
                      onClick={() => {
                        RouterUtil.navigateTo(
                          '/pages/dress/detail/index',
                          {
                            id: dress.id,
                          },
                        );
                      }}
                    >
                      <View className={styles.dressImageWrapper}>
                        <Media
                          src={dress.shortUrl}
                          className={styles.dressImage}
                          mode="aspectFill"
                        />
                      </View>
                      <View className={styles.dressInfo}>
                        <Text className={styles.dressName}>
                          {dress.dressName}
                        </Text>
                      </View>
                    </View>
                  ))
                ) : (
                  <Empty title="暂无商品" />
                )}
              </View>
            </Tabs.TabPane>
          ))}
        </Tabs>
      </View>

      {/* 化妆摄影模块 */}
      <View className={styles.makeupSection}>
        <View className={styles.sectionHeader}>
          <Text className={styles.sectionTitle}>化妆摄影</Text>
          {makeupList.length > 0 && (
            <View
              className={styles.moreIcon}
              onClick={() => {
                RouterUtil.switchTab('/pages/makeup/index/index', {
                  type: activeMakeupTab,
                });
              }}
            >
              <Icon name="RightOutlined" size={16} />
            </View>
          )}
        </View>
        <Tabs
          value={activeMakeupTab}
          onChange={(value) => {
            setActiveMakeupTab(Number(value));
          }}
          align="left"
        >
          {fourGreatTypeList.map((type) => (
            <Tabs.TabPane title={type.text} key={type.value} value={type.value}>
              <View className={styles.makeupGrid}>
                {makeupList.length > 0 ? (
                  makeupList.map((item) => (
                    <View
                      key={item.id}
                      className={styles.makeupCard}
                      onClick={() => {
                        RouterUtil.navigateTo(
                          '/pages/makeup/detail/index',
                          {
                            id: item.id,
                            type: activeMakeupTab,
                          },
                        );
                      }}
                    >
                      <View className={styles.makeupImageWrapper}>
                        <Media
                          src={getMakeupPictureUrl(item)}
                          className={styles.makeupImage}
                          mode="aspectFill"
                        />
                      </View>
                      <View className={styles.makeupInfo}>
                        <Text className={styles.makeupName}>{item.name}</Text>
                      </View>
                    </View>
                  ))
                ) : (
                  <Empty title={`暂无${type.text}信息`} />
                )}
              </View>
            </Tabs.TabPane>
          ))}
        </Tabs>
      </View>
    </BasicLayout>
  );
}

export default Home;
